import re
import platform
import subprocess
import logging
import gw_report_tool

logger = logging.getLogger('cmd_tool')


def exec_cmd(cmd):
    logger.info('exec cmd: ' + cmd)

    cmd = cmd.replace('\\', '/')
    cmd = re.sub('/+', '/', cmd)

    if platform.system() == 'Windows':
        sub_process = subprocess.STARTUPINFO
        sub_process.dwFlags = subprocess.STARTF_USESHOWWINDOW
        sub_process.wShowWindow = subprocess.SW_HIDE
        cmd = str(cmd).encode('gbk')

    s = subprocess.Popen(cmd, shell=True)
    ret = s.wait()

    if ret:
        s = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        std_output, err_output = s.communicate()
        gw_report_tool.send_err_to_srv(cmd, std_output, err_output)
        cmd += 'exec error : '
        logger.error(cmd)
    else:
        cmd += 'exec success : '
        logger.info(cmd)

    return ret